#include "updatenotification.h"

#include <QNetworkAccessManager>
#include <QCryptographicHash>
#include <QStatusBar>
#include <QLabel>
#include "global/path.h"
#include "global/global.h"
#include "global/config.h"
#include "mainwindow.h"

#include <iostream>

UpdateNotification olive::update_notifier;

UpdateNotification::UpdateNotification()
{

}
#if 0
void UpdateNotification::getNoticeContent(QString noticeUrl)
{

  QNetworkAccessManager* manager = new QNetworkAccessManager();

  connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(finished_notice(QNetworkReply *)));
  connect(manager, SIGNAL(finished(QNetworkReply *)), manager, SLOT(deleteLater()));
  QUrl url(noticeUrl);
  QNetworkRequest request(url);
  manager->get(request);

}
void UpdateNotification::finished_notice(QNetworkReply* reply)
{
  if(reply == nullptr)
  {
    return;
  }
  //QByteArray ba = QCryptographicHash::hash(reply.readAll(), QCryptographicHash::Md5);  
  
}
#endif
void UpdateNotification::check()
{

  QNetworkAccessManager* manager = new QNetworkAccessManager();

  connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(finished_slot(QNetworkReply *)));
  connect(manager, SIGNAL(finished(QNetworkReply *)), manager, SLOT(deleteLater()));

  QString update_url = QString("http://www.sumoon.com/kungang/latest.txt");
  QUrl url(update_url);
  QNetworkRequest request(url);
  manager->get(request);

}
void UpdateNotification::downloadNotice()
{
  qWarning() << " downloading notice:" << noticeUrl ;
  QNetworkAccessManager* manager = new QNetworkAccessManager();

  connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(finished_notice_slot(QNetworkReply *)));
  connect(manager, SIGNAL(finished(QNetworkReply *)), manager, SLOT(deleteLater()));
  QUrl url(noticeUrl);
  QNetworkRequest request(url);
  manager->get(request);

}

QString UpdateNotification::getNodeContent(const QString& response, const QString& snode, const QString& enode)
{
    int vi = response.indexOf(snode);
    if(vi != -1)
     {
       int vei = response.indexOf(enode, vi);
       if(vei != -1)
       {
        QString lver = response.mid(vi+snode.length(), vei-vi-snode.length());
        return lver;
       }
     }
     return QString();
}
void UpdateNotification::getNoticeNameFromUrl(const QString& noticeUrl)
{
   int vi = noticeUrl.lastIndexOf('/');
   noticeName = noticeUrl.mid(vi+1, noticeUrl.length()-vi-1);

   qWarning() << "noticeName is " << noticeName;
}

void UpdateNotification::finished_notice_slot(QNetworkReply *reply)
{
  if(reply == nullptr || noticeName.length() == 0)
  {
    //No Network;
    return;
  }
  QDir app_dir = QDir(get_app_path());
  QDir destDir(app_dir.filePath("kgnotice"));
  QString tmpFile = destDir.absoluteFilePath(noticeName);
  qWarning() << "finished downloading slot,write file: " << tmpFile;
  QFile *file = new QFile(tmpFile, this);
  if (file && !file->open(QIODevice::WriteOnly)) {
    qInfo() << "Write file error! " << file->errorString() << "\n";
    return;
  }
  QByteArray data = reply->readAll();

  if(file && !data.isEmpty())
  {
    int writeBytes = file->write(data);
    file->flush();
    file->close();
    if (writeBytes != data.size()) {
      qInfo() << "Write file error:" <<  file->errorString() << "\n";
      return;
    }
    if(writeBytes < noticeSize)
      {
      qInfo() << "File size error:" <<  writeBytes << "\n";
      return;
      }
    olive::CurrentConfig.current_notice_file = noticeName;
    
    //QTimer::singleShot(50, olive::MainWindow, SLOT(load_notice_media()));
  }
}
void UpdateNotification::finished_slot(QNetworkReply *reply)
{
  if(reply == nullptr)
  {
    //No Network;
    return;
  }
  QString response = QString::fromUtf8(reply->readAll());

  
  //JlCompress::extractDir("D:/testzip/a.zip", "D:/testzipdir2");
  //qInfo()<< "check update done, with response:" << response ;
   
  /*
  <version>
  <build>
  <date>
  <url>
  <notes>
  */
  if(!response.isEmpty())
  {
     QString lver = getNodeContent(response, "<version>", "</version>");
     QString lbuild = getNodeContent(response, "<build>", "</build>");
     QString ldate = getNodeContent(response, "<date>", "</date>");
     QString lnote = getNodeContent(response, "<note>", "</note>");
     QString url = getNodeContent(response, "<url>", "</url>");
     QString relnum = getNodeContent(response, "<release>", "</release>");
     noticeUrl = getNodeContent(response, "<noticeurl>", "</noticeurl>");
        
     noticeSize = getNodeContent(response, "<noticesize>", "</noticesize>").toInt();
     qInfo()<< "v:" << lver << " lb" << lbuild << " rn:" << relnum << "\n";
     if(!lver.isEmpty() && !lbuild.isEmpty() && (lver != version_str || lbuild != build_str) && relnum.toInt() > release_num)
     {
        if(lnote.isEmpty())
          lnote = QString(tr("There is new version:%1.%2 for download")).arg(lver,lbuild);
        QLabel* lbl = new QLabel(QString("<a href=\"http://www.kungang.xyz/#download\">%1</a>").arg(lnote),olive::MainWindow);
        olive::MainWindow->statusBar()->addPermanentWidget(lbl, 1);
        connect(lbl,SIGNAL(linkActivated(QString)),  olive::Global.get(),SLOT(openUrl(QString)));
         //olive::MainWindow->statusBar()->showMessage(lnote);
        //QLabel *lbl=new QLabel("Widget");
        //olive::MainWindow->statusBar()->addPermanentWidget(lbl);
     }
     else
     {
        olive::MainWindow->statusBar()->showMessage(tr("Latest version"));
     }
     if(noticeUrl.length() > 0)
      {
       getNoticeNameFromUrl(noticeUrl);
       if(olive::CurrentConfig.current_notice_file != noticeName)
       {
       QTimer::singleShot(50, this, SLOT(downloadNotice()));
       }
      }
  }
}
